#include "hj212_data_msg/hj212_data_msg.h"
#include "hj212_pack.h"

/* *
 * 基本数据打包
 * 1. 一般实时数据打包
 * 2. 一般历史数据打包
 */

int hj212_datamsg_pack_rtdata(struct hj212_datamsg *msg, int protocol, struct timeval precise_time, int item_maxlen, char *buffer, int len)
{
#define TMP_SIZE    (256)
    char tmp[TMP_SIZE];
    char *qn = NULL;
    if (protocol == HJ212_PROTOCOL_2017)
    {
        hj212_generate_qn(msg->parent.qn, HJ212_QN_MAX_LEN, precise_time);
        qn = msg->parent.qn;
    }
    hj212_pack_head_pnum(qn, msg->parent.st, msg->parent.cn,
                         msg->parent.access_pwd, msg->parent.mn,
                         msg->parent.flag, msg->pnum, msg->pno + 1,
                         (char *)buffer, len);
    hj212_pack_datatime(tmp, TMP_SIZE, msg->datatime);
    hj212_pack_add_field((char *)buffer, len, tmp);
    int count = 0;
    for (count = 0; count < item_maxlen; count++)
    {
        struct pol_rtval rtval;
        if (gen_blk_queue_read_offset(&msg->queue, (void *)&rtval, count, 1) == 1)
        {
            hj212_pack_rtdata(tmp, TMP_SIZE, &rtval);
            hj212_pack_add_field((char *)buffer, len, tmp);
        }
        else
            break;
    }
    hj212_pack_end((char *)buffer, len);
    return count;
}

int hj212_datamsg_pack_hisdata(struct hj212_datamsg *msg, int protocol, struct timeval precise_time, int item_maxlen, char *buffer, int len)
{
#define TMP_SIZE    (256)
    char tmp[TMP_SIZE];
    char *qn = NULL;
    if (protocol == HJ212_PROTOCOL_2017)
    {
        hj212_generate_qn(msg->parent.qn, HJ212_QN_MAX_LEN, precise_time);
        qn = msg->parent.qn;
    }
    hj212_pack_head_pnum(qn, msg->parent.st, msg->parent.cn,
                         msg->parent.access_pwd, msg->parent.mn,
                         msg->parent.flag, msg->pnum, msg->pno + 1,
                         (char *)buffer, len);
    hj212_pack_datatime(tmp, TMP_SIZE, msg->datatime);
    hj212_pack_add_field((char *)buffer, len, tmp);
    int count = 0;
    for (count = 0; count < item_maxlen; count++)
    {
        struct pol_his_data hisval;
        if (gen_blk_queue_read_offset(&msg->queue, (void *)&hisval, count, 1) == 1)
        {
            hj212_pack_hisdata(tmp, TMP_SIZE, &hisval);
            hj212_pack_add_field((char *)buffer, len, tmp);
        }
        else
            break;
    }
    hj212_pack_end((char *)buffer, len);
    return count;
}
